/*
 * 文 件 名 : HomeActivity.java
 * 版    权 : China Machi.Co.,Ltd.Copyright 2009-2011.All rights reserved
 * 描    述 : <描述>
 * 修 改 人 : lixg
 * 修改时间 : 2012-8-4
 * 跟踪单号 : <跟踪单号>
 * 修改单号 : <修改单号>
 * 修改内容 : <修改内容>
 */
package com.fire8.dolphin.ui.more;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.fire8.dolphin.db.FriendDAO;
import com.fire8.dolphin.model.UserInfo;
import com.fire8.dolphin.service.JaberClientService;
import com.fire8.dolphin.ui.DolphinApplication;
import com.fire8.dolphin.ui.R;
import com.fire8.dolphin.utils.LogUtil;
import com.fire8.dolphin.utils.MD5;
import com.fire8.dolphin.utils.StringUtil;
import com.fire8.dolphin.web.RequestUtils;

/**
 * 主页面
 * 显示全部问题
 *
 * @author  lixg
 * @version [版本号,2012-8-4]
 * @see     [相关类/方法]
 * @since   [产品/模块]
 */
public class LoginActivity extends Activity
{
    private EditText txtAccount;
    
    private EditText txtPassword;
        
    private Button btnEnter;
    
    private String strAccount;
    
    private String strPassword;
    
    private DolphinApplication app;
    private JaberClientService jaberClientService;
    private String msg;//网络提示信息
    private StringBuffer url = new StringBuffer(DolphinApplication.URL);
    private ProgressDialog progressDialog = null;
    private FriendDAO friendDao;
    boolean success;
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        getElement();
        setElementEvent();
        app = (DolphinApplication)getApplication();
        jaberClientService = JaberClientService.getInstance();
        friendDao = new FriendDAO(this);
    }
    
    private void getElement()
    {
        btnEnter = (Button)findViewById(R.id.btn_enter);
        txtAccount = (EditText)findViewById(R.id.txt_account);
        txtPassword = (EditText)findViewById(R.id.txt_password);
        
    }
    
    private void setElementEvent()
    {
        txtAccount.requestFocus();
        btnEnter.setOnClickListener(new OnClickListener()
        {
            
            @Override
            public void onClick(View v)
            {
                strAccount = txtAccount.getText().toString();
                strPassword = txtPassword.getText().toString();
                if (StringUtil.isEmpty(strAccount)
                        || StringUtil.isEmpty(strPassword))
                {
                    Toast.makeText(LoginActivity.this,
                            "请输入账号或密码",
                            Toast.LENGTH_LONG).show();
                    return;
                }
                
                //打开进度条窗口
                progressDialog = ProgressDialog.show(LoginActivity.this, "请稍等...", "登录系统...", true);
                //执行提交任务
                new RegisterTask().execute(null);
            }
        });
        
    }
    
    class RegisterTask extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            if(!RequestUtils.getInstall().isConnect(LoginActivity.this))
            {
                return "网络不可用";
            }
            String userId=null;
            LogUtil.d("登录:");
            LogUtil.d("密码:"+strPassword);
            try
            {
                jaberClientService.connect();
                jaberClientService.login(strAccount, strPassword);
                
                //获取用户对应的userId
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("account",strAccount));
                param.add(new BasicNameValuePair("password",MD5.code(strPassword)));
                String json = RequestUtils.getInstall().getHttpJson(url.append("user/login.php").toString(), param);
                LogUtil.d(json);
                if(StringUtil.isEmpty(json))
                {
                    throw new Exception("登录失败");
                }
                
                JSONObject data = new JSONObject(json);
                String msgCode = data.getString("msgCode");
                //String desc = data.getString("desc");
                if("1".equals(msgCode))
                {
                    JSONObject obj = data.getJSONObject("msgBody");
                    userId = obj.getString("userId");
                    LogUtil.d("登录成功："+userId);
                    UserInfo user = new UserInfo();
                    user.setUserName(obj.getString("userName"));
                    user.setUserType(obj.getInt("userType"));
                    user.setUserTitle(obj.getString("userTitle"));
                    user.setPoint(obj.getInt("point"));
                    user.setRemark(obj.getString("remark"));
                    app.setUserInfo(user);
                }else
                {
                    throw new Exception(data.getString("desc"));
                }
                
                
                success=true;
                
            }
            catch (Exception e)
            {
                LogUtil.e("连接openfire服务器失败", e);
                jaberClientService.disConn();
                return "登录失败";
            }
            
            try
            {
                LogUtil.d("同步好友");
                //同步好友
                List<NameValuePair> param = new ArrayList<NameValuePair>();
                param.add(new BasicNameValuePair("userId",userId));
                RequestUtils.getInstall().findFriendList(param,friendDao);
                
            }
            catch (Exception e)
            {
                LogUtil.e("同步好友失败", e);
                return "同步好友失败";
            }
            return userId;
        }
        @Override
        protected void onPostExecute(String result)
        {
            super.onPostExecute(result);
            
            //关闭进度条窗口
            progressDialog.dismiss();
            if(success)
            {
                LogUtil.d("将用户ID及账号密码写入到本地");
                app.setAccount(strAccount, strPassword);
                //将用户ID写入本地
                app.setUserId(result);
                //如果登录成功，将注册窗口关闭
                LoginActivity.this.finish();
            }else
            {
                LogUtil.d(result);
                Toast.makeText(LoginActivity.this, result, Toast.LENGTH_LONG).show();
            }
            
        }
    }
    
}
